extends CharacterBody2D
class_name Bullet
static var bullet=preload("res://scenes/bullet.tscn")

var cache_vx:float=0
var cache_vy:float=0

var stay_time:float=0
var hit_count:int=0
var fading:bool=false

func _physics_process(delta: float) -> void:
	
	cache_vx=velocity.x
	cache_vy=velocity.y
	move_and_slide()
	
	if is_on_wall():
		velocity.x=-cache_vx
		$AudioStreamPlayer.play()
	if is_on_ceiling() or is_on_floor():
		velocity.y=-cache_vy
		$AudioStreamPlayer.play()
	
	
	stay_time+=delta
	if stay_time>=15.0:
		fade()
	
func fade():
	if fading:
		return
	fading=true
	var tween=create_tween()
	$Area2D/CollisionShape2D.disabled=true
	tween.tween_property($Sprite2D,"modulate:a",0.0,0.2)
	await tween.finished
	queue_free()

static func generate_bullet(direction:Vector2,pos:Vector2):
	var blt = bullet.instantiate()
	blt.velocity=direction*40.0
	blt.position=pos
	return blt
	


func _on_area_2d_body_entered(body: Node2D) -> void:
	hit_count+=1
	if hit_count>1 and body is Tank:
		body.die()
		fade()
